package util;

import lib.logging.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by IntelliJ IDEA.
 * User: lodder
 * Date: 19/04/11
 * Time: 21:06
 * To change this template use File | Settings | File Templates.
 */
public class Downloader {

    public static boolean doDownloadFile(URL url, final File file) {
        boolean success = true;
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(file);
            final BufferedInputStream in;
            if (url.getFile().endsWith(".gz")) {
                in = new BufferedInputStream(new GZIPInputStream(url.openStream()));
            }else {
            	//check if the response code is a redirect, if redirect use the new location as the new URL
            	HttpURLConnection urlC = (HttpURLConnection) url.openConnection();
            	urlC.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            	urlC.setInstanceFollowRedirects(false);
            	urlC.connect();
            	if (urlC.getResponseCode() == 302)
            		url = new URL(urlC.getHeaderField("Location"));
            	urlC.disconnect();
            	HttpURLConnection http = (HttpURLConnection) url.openConnection();
            	http.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                in = new BufferedInputStream(http.getInputStream());
            }

            final BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
            final byte data[] = new byte[1024];
            int x;
            while ((x = in.read(data, 0, 1024)) >= 0) {
                bout.write(data, 0, x);
            }
            bout.close();
            in.close();
            if(url.getFile().endsWith(".zip")){
                unzip(file);
            }
        } catch (Exception e) {
            success = false;
            Logger.instance.error("Download problem: " + e.getMessage());
        }
        return success;
    }

    private static void unzip(File file) throws IOException {
        Files.move(file, new File(file.getAbsolutePath().replace(".srt", ".zip")));
        FileInputStream fin = new FileInputStream(new File(file.getAbsolutePath().replace(".srt", ".zip")));
        ZipInputStream zin = new ZipInputStream(fin);
        ZipEntry ze;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.getName().endsWith(".srt")){
                FileOutputStream fout = new FileOutputStream(file);
                final BufferedOutputStream bout = new BufferedOutputStream(fout, 1024);
                final byte data[] = new byte[1024];
                int x;
                while ((x = zin.read(data, 0, 1024)) >= 0) {
                    bout.write(data, 0, x);
                }
                fout.close();
                zin.closeEntry();
            }
        }
        zin.close();
        new File(file.getAbsolutePath().replace(".srt", ".zip")).delete();
    }

    public static String getUrlContents(URLConnection conn) throws IOException {
        StringBuilder content = new StringBuilder();
        // wrap the urlconnection in a bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        //Logger.instance.log(conn.getRequestProperty("user-agent"));
        String line;

        // read from the urlconnection via the bufferedreader
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line).append("\n");
        }
        bufferedReader.close();
        return content.toString();
    }
}
